<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/5 0005
 * Time: 13:54
 */
namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;

class EntryLogin extends ActiveRecord
{


    public static function tableName () {
        return 'admin';
    }

    private $user;

    public function rules()
    {
        return [
            [['username','pwd'],'required'],
            ['pwd','validatePwd']
        ];
    }
    
    
    public function validatePwd($attributes , $params){
        if(!$this->hasErrors()){
            $user = $this->getUser($this->attributes['username']);
            if(!$user || !$this->validatePassword($this->attributes['pwd'])){
                $this->addError($attributes,'密码错误');
            }
        }
    }

    public function login(){
        if($this->validate()){
            return Yii::$app->user->login($this->getUser($this->attributes['username']),$this->attributes['rememberMe'] ? 3600*24*30 : 0);
        }
        return false;
    }


    private function getUser($username) {
        return $this->user = Admin::find()
            ->where(['username'=>$username])
            ->one();
    }

    private function validatePassword($password){

        //密码加密为mysql password函数加密
        return $this->user['pwd'] === strtoupper(md5($password));
    }

}